package website.haicheng.server.handlers;

import cn.hutool.core.date.DateUtil;
import website.haicheng.server.common.annotations.Handler;
import website.haicheng.server.common.constant.AttrConstant;
import website.haicheng.server.common.enums.MessageEnum;
import website.haicheng.server.config.NettyManage;
import website.haicheng.server.model.Message;
import website.haicheng.server.model.vo.Resp;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 上线处理
 * @Date: Created in 2021/12/1 16:26
 */
@Slf4j
@Handler(value = MessageEnum.OPEN_CHANNEL)
@Component
public class OpenHandler implements MessageHandler {

    @Resource
    private NettyManage nettyManage;

    /**
     * 逻辑处理
     *
     * @param channel Channel
     * @param message Message
     */
    @Override
    public void process(Channel channel, Message message) {
        // 获取channelId
        Map<String, String> data = message.getData();
        String account = data.get("account");

        if (nettyManage.alreadyLogin(account)) {
            channel.writeAndFlush(Resp.fail("用户已登录"));
            return;
        }

        // 写入本地内存
        nettyManage.addChannel(channel);
        nettyManage.addUser(account, channel);
        // 设置认证成功标签
        channel.attr(AttrConstant.ATTRIBUTE_KEY_STATUS).set(HttpStatus.OK.getReasonPhrase());
        channel.attr(AttrConstant.ATTRIBUTE_KEY_TIME).set(DateUtil.now());
        channel.attr(AttrConstant.ATTRIBUTE_KEY_ACCOUNT).set(account);

        channel.writeAndFlush(Resp.ok());
    }
}
